const fs = require("fs");
const path = require("path");

function ls(directoryPath, pattern = "*") {
  return new Promise((resolve, reject) => {
    fs.readdir(directoryPath, (err, files) => {
      if (err) {
        if (err.errno === -2) {
          resolve({ fileList: null });
        }
        reject(err);
        return;
      }

      const regex = new RegExp(`^${pattern.replace(/\*/g, ".*")}$`, "g");
      const matchedFiles = files.filter((file) => regex.test(file));
      matchedFiles.sort((a, b) => {
        const fileNumberA = parseInt(a.match(/\d+/)[0]);
        const fileNumberB = parseInt(b.match(/\d+/)[0]);
        return fileNumberA - fileNumberB;
      });

      resolve({ fileList: matchedFiles });
    });
  });
}

module.exports = {
  ls,
};
